package table_user

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/klein-x/biz/model/mysql/table"
	"gitee.com/klein-x/biz/module/db/mysql"
	"gitee.com/klein-x/biz/xutils"
	"gorm.io/gorm"
)

// AnswerCard 存储用户答题卡
// TODO: 试卷中有试卷总分和及格分数,答题卡中缺少当前分数
type UserAnswerCard struct {
	CardID            string              `gorm:"primaryKey;type:char(36);unique;not null;comment:'答题卡ID'"`
	UserUUID          string              `gorm:"type:char(36);not null;comment:'用户UUID'"`
	PaperID           string              `gorm:"type:char(36);not null;comment:'试卷ID'"`
	Answers           map[string][]string `gorm:"type:text;serializer:json;not null;comment:'用户的答案,JSON格式'"`
	TotalQuestions    uint                `gorm:"comment:'题目总数'"`
	CorrectQuestions  uint                `gorm:"comment:'正确题目数'"`
	WrongQuestions    uint                `gorm:"comment:'错误题目数'"`
	UnanswerQuestions uint                `gorm:"comment:'未做题目数'"`
	CreatedAt         time.Time           `gorm:"comment:'创建时间'"`
	UpdatedAt         time.Time           `gorm:"comment:'更新时间'"`
	DeletedAt         gorm.DeletedAt      `gorm:"comment:'软删除时间'"`
}

// TableName 实现 GORM 的 TableName 接口，自定义表名
func (ac *UserAnswerCard) TableName() string {
	return "user_answer_cards"
}

// 默认UserAnswerCard
func AnswerCardDefine(uuid, paperId string) *UserAnswerCard {
	var answerCard UserAnswerCard
	id, err := xutils.RandomUUID()
	if err != nil {
		return nil
	}
	answerCard.CardID = id
	answerCard.UserUUID = uuid
	answerCard.PaperID = paperId
	answerCard.Answers = make(map[string][]string)
	answerCard.TotalQuestions = 0
	answerCard.CorrectQuestions = 0
	answerCard.WrongQuestions = 0
	answerCard.UnanswerQuestions = 0
	return &answerCard
}

// 获取答题卡-user&paper
func AnswerCardGetByUserAndPaper(uuid string, paperID string) (*UserAnswerCard, error) {
	db := mysql.GetGlobalDB()
	var answerCard UserAnswerCard
	return table.SelectCheck(&answerCard, db.Where("user_uuid = ? AND paper_id = ?", uuid, paperID).First(&answerCard))
}

// 获取答题卡-uuid
func AnswerCardGetByID(answerCardId string) (*UserAnswerCard, error) {
	db := mysql.GetGlobalDB()
	var answerCard UserAnswerCard
	return table.SelectCheck(&answerCard, db.Where("card_id = ?", answerCardId).First(&answerCard))
}

// 答题卡记录数
func AnswerCardCount(uuid, paperId string) (int64, error) {
	db := mysql.GetGlobalDB()

	var count int64
	err := db.Model(&UserAnswerCard{}).Where("user_uuid = ? AND paper_id = ?", uuid, paperId).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// 插入答题卡
func AnswerCardInsert(anscard *UserAnswerCard) error {
	db := mysql.GetGlobalDB()
	return table.InsertCheck(db.Create(anscard))
}

// 更新答题卡
func AnswerCardUpdate(anscard *UserAnswerCard) error {
	db := mysql.GetGlobalDB()
	ansjson, err := json.Marshal(anscard.Answers)
	if err != nil {
		return fmt.Errorf("序列化json失败, %v", err)
	}
	values := map[string]interface{}{
		"answers":            ansjson,
		"total_questions":    anscard.TotalQuestions,
		"correct_questions":  anscard.CorrectQuestions,
		"wrong_questions":    anscard.WrongQuestions,
		"unanswer_questions": anscard.UnanswerQuestions,
	}

	return table.UpdateCheck(db.Model(&UserAnswerCard{}).
		Where("user_uuid = ? AND paper_id = ?", anscard.UserUUID, anscard.PaperID).
		Updates(values))
}
